import 'dart:io';

import 'package:cave_flutter/common/common_widget.dart';
import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/network/whl_result_data.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/utils/whl_dialog_util.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:cave_flutter/widgets/whl_button.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';

class AppVersion {
  static AppVersion? _instance;
  static Directory? dir;

  static AppVersion getInstance() {
    _instance ??= AppVersion._internal();
    _instance!.initSDK();
    return _instance!;
  }

  initSDK() async {
    dir = await getExternalStorageDirectory();
  }

  AppVersion._internal();

  /// 是否正在检测版本
  bool isChecking = false;

  /// 检测是否有新版本更新
  void check() async {
    // if (isChecking) return;
    // isChecking = true;
    VersionModel? version;
    PackageInfo? packageInfo;
    try {
      isChecking = true;
      // 获取应用的信息
      packageInfo = WHLGlobalConfig.packageInfo;
      ResponseData responseData = await WhlApi.getAppVersion.get({});
      if (responseData.isSuccess()) {
        version = VersionModel.fromJson(responseData.data);
        int remoteVersionNumber = int.parse(version.versionNumber!);
        int currentVersion = int.parse(packageInfo.buildNumber);
        if (currentVersion < remoteVersionNumber && version.url != null) {
          showDownloadDialog(version);
        }
      }
      // version = await VersionApi().version(packageInfo.buildNumber);
    } catch (e) {
    } finally {
      isChecking = false;
    }
  }

  showDownloadDialog(VersionModel version) {
    if (version.url != null && version.url!.isNotEmpty) {
      Get.dialog(
        DownloadAppWidget(
          versionModel: version,
        ),
      ).then((value) {
        print(value);
      });
    }
  }
}

class DownloadAppWidget extends StatefulWidget {
  final VersionModel versionModel;

  const DownloadAppWidget({Key? key, required this.versionModel})
      : super(key: key);

  @override
  _DownloadAppWidgetState createState() => _DownloadAppWidgetState();
}

class _DownloadAppWidgetState extends State<DownloadAppWidget> {
  late ValueNotifier<double> progressValue;
  // 0是否更新 1正在下载 2安装 -1下载异常
  late ValueNotifier<int> statusValue;

  static late Directory apksDir;
  static late String savePath;
  static late String tmpSavePath;

  @override
  void initState() {
    super.initState();
    apksDir = AppVersion.dir!;
    progressValue = ValueNotifier<double>(0);
    statusValue = ValueNotifier<int>(0);
  }

  @override
  void dispose() {
    statusValue.dispose();
    progressValue.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: ValueListenableBuilder<int>(
        valueListenable: statusValue,
        builder: (context, int status, Widget? child) {
          return Center(
            child: UIColumn(
              mainAxisSize: MainAxisSize.min,
              width: double.maxFinite,
              radius: 30.w,
              margin: EdgeInsets.symmetric(horizontal: 34.w),
              color: Colors.white,
              children: [
                UIText(
                  text: '版本更新提示',
                  fontSize: 17.sp,
                  textColor: kAppTextColor,
                  fontWeight: FontWeight.bold,
                  margin: EdgeInsets.only(top: 16.h, bottom: 14.h),
                ),
                _contentWidget(status),
                status == 1
                    ? SizedBox(
                        height: 40.h,
                      )
                    : UIRow(
                        margin: EdgeInsets.symmetric(
                            horizontal: 100.w, vertical: 20.h),
                        children: [
                          Expanded(
                              child: UISolidButton(
                            height: 42.h,
                            text: _rightButtonText(status),
                            color: Colors.black,
                            onTap: () {
                              //  if (status != 0 || await canLaunch(widget.versionModel.url!)) {
                              String? url = widget.versionModel.url;
                              if (url != null && url.isNotEmpty) {
                                if (status == 0) {
                                  download(url);
                                } else if (status == 1) {
                                  Navigator.of(context).pop();
                                } else if (status == -1) {
                                  download(url);
                                } else if (status == 2) {
                                  InstallPlugin.install(savePath).then((value) {
                                    print(value);
                                  });
                                  // UpdateApp.installApp(path: ctrl.savePath);
                                }
                              } else {
                                MyToast.show('Could not launch ${url}');
                                Navigator.of(context).pop();
                              }
                            },
                          )),
                        ],
                      )
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _contentWidget(int status) {
    if (status == 0) {
      return UIText(
        text: widget.versionModel.remark ?? '发现新版本是否进行更新',
      );
    } else if (status == 1 || status == -1) {
      return ValueListenableBuilder(
          valueListenable: progressValue,
          builder: (context, value, child) {
            return UIColumn(
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: UIText(
                      text: status == 1
                          ? '正在下载${(progressValue.value * 100).toStringAsFixed(2)}%'
                          : '下载失败，请重试'),
                ),
                LinearProgressIndicator(
                  borderRadius: BorderRadius.circular(8),
                  value: value,
                  minHeight: 6.0.w,
                  backgroundColor: Colors.white.withOpacity(0),
                  valueColor:
                      const AlwaysStoppedAnimation<Color>(Colors.greenAccent),
                )
              ],
            );
          });
    } else if (status == 2) {
      return const Center(
        child: UIText(text: '下载完成'),
      );
    } else {
      return const SizedBox();
    }
  }

  String _rightButtonText(int status) {
    String text;
    switch (status) {
      case 0:
        text = '立即更新';
        break;
      case 1:
        text = '取消下载';
        break;
      case -1:
        text = '继续下载';

        break;
      case 2:
        text = '立即安装';
        break;
      default:
        text = '确定';
        break;
    }
    return text;
  }

//  下载app
  Future<void> download(String appUrl) async {
    savePath = '${apksDir.path}/app_${widget.versionModel.versionNumber}.apk';
    tmpSavePath = '$savePath.tmp';

    // 删除目录下过期和历史的apk文件
    Stream<FileSystemEntity> entityList =
        apksDir.list(recursive: false, followLinks: false);
    await for (FileSystemEntity entity in entityList) {
      String path = entity.path;
      // 过滤掉已下载最新的apk
      if (path != savePath) {
        entity.deleteSync(recursive: true);
      }
    }
    Dio dio = Dio();
    statusValue.value = 1;
    return dio.download(
      appUrl,
      tmpSavePath,
      onReceiveProgress: (int count, int total) {
        progressValue.value = count / total;
      },
    ).then((value) {
      if (value.statusCode == 200) {
        statusValue.value = 2;
        File(tmpSavePath).renameSync(savePath);
      } else {
        statusValue.value = -1;
      }
    }, onError: (error) {
      statusValue.value = -1;
    });
  }
}

class VersionModel {
  String? id;
  String? pubTime;
  String? remark;
  int? type;
  String? url;
  String? versionNumber;
  VersionModel(
      {this.id,
      this.pubTime,
      this.remark,
      this.type,
      this.url,
      this.versionNumber});

  VersionModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    pubTime = json['pubTime'];
    remark = json['remark'];
    type = json['type'];
    url = json['url'];
    versionNumber = json['versionNumber'];
  }
}
